<?php
// +----------------------------------------------------------------------
// | Description: 用户组
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use app\common\exception\ExceptionEmun;
use app\common\exception\SystemException;
use Helper\ArrayHelper;
use app\common\model\base\BaseModel;
use app\common\traits\InstanceTrait;
use think\facade\Db;
use think\Model;
use think\model\Pivot;

class MemberGroup extends BaseModel
{
    use InstanceTrait;

    const STATUS_ON = 1;
    const STATUS_OFF = 2;
    protected static $status_translate = [
        self::STATUS_ON => '启用',
        self::STATUS_OFF => '禁用',
    ];

    public function __construct($data = [], Model $parent = null, $table = '')
    {
        parent::__construct($data, $parent, $table);
        $this->pk = 'group_id';
        $this->initBaseField();
    }

    /**
     * 获取列表
     * @return mixed|Model|Pivot|null
     */
    public function getList($param)
    {
        $where = $this->getBaseWhere($param);
        $param['page'] = !empty($param['page']) ? $param['page'] : 1;
        $param['limit'] = !empty($param['limit']) ? $param['limit'] : 15;
        $data = static::where($where)
                      ->field($this->baseField)
                      ->page($param['page'], $param['limit'])
                      ->select();
        return $data;
    }

    /**
     * [createData 新建]
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param array $param [description]
     * @return bool [array]                         [description]
     * @throws Exception
     */
    public function createData($param)
    {
        $this->startTrans();
        try {
            $group = static::create($param);
        } catch (Exception $e) {
            throw $e;
        }
        //写入中间表
        $group_id = $group->group_id;

        $this->insertRuleRelation($group_id, $param['rules']);
        $this->insertMenuRelation($group_id, $param['menus']);

        $this->commit();
        return true;
    }

    /**
     * MemberGroupRuleRelation中间表写入
     * @param $group_id
     * @param $member_id
     * @param $rules
     */
    protected function insertRuleRelation($group_id, $rules)
    {
        $rules = ArrayHelper::ToTree($rules);
//        循环插入太慢,废弃
//        $res = $this->rules()->saveAll($rules);
        $data = MemberGroupRuleRelation::beforeInsertData(['group_id' => $group_id]);
        $insertAllDate = [];
        foreach ($rules as $key => $value) {
            $insertAllDate[$key] = $data;
            $insertAllDate[$key]['rule_id'] = $value;
        }
        Db::table(MemberGroupRuleRelation::instance()->getTable())->insertAll($insertAllDate);
        return true;
    }

    /**
     * MemberGroupMenuRelation中间表写入
     * @param $group_id
     * @param $member_id
     * @param $menus
     */
    protected function insertMenuRelation($group_id, $menus)
    {
        $menus = ArrayHelper::ToTree($menus);
//        循环插入太慢,废弃
//        $res = $this->menus()->saveAll($menus);
        $data = self::beforeInsertData(['group_id' => $group_id]);
        $insertAllDate = [];
        foreach ($menus as $key => $value) {
            $insertAllDate[$key] = $data;
            $insertAllDate[$key]['menu_id'] = $value;
        }
        Db::table(MemberGroupMenuRelation::instance()->getTable())->insertAll($insertAllDate);

        return true;
    }

    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param $param
     * @param $id
     * @return bool [type]                          [description]
     * @throws Exception
     */
    public function updateByID($param, $group_id)
    {
        $this->startTrans();
        $checkData = $this->find($group_id);
        if (!$checkData) {
            ExceptionEmun::throwException(SystemException::INVALID_PARAMETER);
        }
        $param[$this->getPk()] = $group_id;
        // 验证
        try {
            $checkData->save($param);
        } catch (Exception $e) {
            throw $e;
        }
        //删除group的中间表rule关联
        $this->rules()->detach();
        //删除group的中间表menu关联
        $this->menus()->detach();
        //写入中间表
        $this->insertRuleRelation($group_id, $param['rules']);
        $this->insertMenuRelation($group_id, $param['menus']);

        $this->commit();
        return true;
    }

    public function rules()
    {
        return $this->belongsToMany(MemberRule::class, MemberGroupRuleRelation::class, 'rule_id', 'group_id')
                    ->alias('rule')
                    ->cache(TRUE, 60)
                    ->field(['rule.*', 'rule.rule_id as id'])
                    ->hidden($this->pivotHiddenField)
                    ->where('status', '=', 1);
    }

    public function menus()
    {
        return $this->belongsToMany(MemberMenu::class, MemberGroupMenuRelation::class, 'menu_id', 'group_id')
                    ->alias('menu')
                    ->cache(TRUE, 60)
                    ->field(['menu.*', 'menu.menu_id as id'])
                    ->order('sort', 'desc')
                    ->hidden($this->pivotHiddenField)
                    ->where('status', '=', 1);
    }

    public function members()
    {
        return $this->belongsToMany(Member::class, MemberGroupRelation::class, 'member_id', 'group_id')
                    ->alias('member')
                    ->field(['member.*', 'member.member_id as id'])
                    ->hidden($this->pivotHiddenField)
                    ->where('status', '=', 1);
    }
}
